package com.kantboot.functional.pay.order.service.impl;

import com.kantboot.functional.pay.order.module.dto.FunctionPayOrderDTOOfOrderPaidAfter;
import com.kantboot.functional.pay.order.module.entity.FunctionalPayOrder;
import com.kantboot.functional.pay.order.repository.FunctionalPayOrderRepository;
import com.kantboot.functional.pay.order.service.IFunctionalPayOrderService;
import com.kantboot.system.user.service.ISysUserService;
import com.kantboot.util.common.exception.BaseException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class FunctionalPayOrderServiceImpl implements IFunctionalPayOrderService {

    @Resource
    private FunctionalPayOrderRepository repository;

    @Resource
    private ISysUserService userService;


    @Override
    public FunctionalPayOrder generatePayOrder(FunctionalPayOrder payOrder) {
        Long selfId = userService.getSelfId();
        // 清除id，防止存入数据库时id冲突
        payOrder.setId(null);
        // 设置发起人的用户id
        payOrder.setUserId(selfId);
        // 设置成未支付状态
        payOrder.setStatusCode(FunctionalPayOrder.STATUS_CODE_UNPAID);
        // 设置成为状态处理
        payOrder.setIsStatusProcessed(false);
        // 设置成为支付处理
        payOrder.setIsPaidAfterCheckProcessed(false);
        return repository.save(payOrder);
    }

    @Override
    public FunctionalPayOrder getById(Long id) {
        return repository.findById(id).orElseThrow(() -> BaseException.of("payOrderNotFound", "支付订单不存在"));
    }

    @Override
    public void updateStatusCodeById(Long id, String statusCode) {
        FunctionalPayOrder functionalPayOrder = getById(id);
        functionalPayOrder.setStatusCode(statusCode);
        if(!FunctionalPayOrder.STATUS_CODE_UNPAID.equals(statusCode)){
            // 如果不是未支付状态，设置成为状态处理设置为true
            functionalPayOrder.setIsStatusProcessed(true);
        }
        repository.save(functionalPayOrder);
    }

    @Override
    public void handlePaidAfter(FunctionPayOrderDTOOfOrderPaidAfter dto){
        FunctionalPayOrder functionalPayOrder = getById(dto.getId());
        // 设置成为支付处理设置为true
        functionalPayOrder.setIsPaidAfterCheckProcessed(true);
        functionalPayOrder.setIsPaidAfterCheckSuccess(dto.getIsPaidAfterCheckSuccess());
        functionalPayOrder.setPaidAfterCheckFailReasonCode(dto.getPaidAfterCheckFailReasonCode());
        functionalPayOrder.setPaidAfterCheckFailReasonDescription(dto.getPaidAfterCheckFailReasonDescription());
        repository.save(functionalPayOrder);
    }

    @Override
    public Boolean checkPaidAfterSuccess(Long id) {
        FunctionalPayOrder order = getById(id);
        if(!order.getIsPaidAfterCheckProcessed()){
            // 如果没有支付处理过，返回false
            return false;
        }

        if(!order.getIsPaidAfterCheckSuccess()){
            throw BaseException.of(order.getPaidAfterCheckFailReasonCode(),order.getPaidAfterCheckFailReasonDescription());
        }

        return true;
    }


}
